import React from 'react';
import Home from "./pages/Home/Home";
import {Detail} from "./pages/Detail/Detail";
import Login from "./pages/Login/Login";
import Register from "./pages/Register/Register";
import {BrowserRouter,Route,Switch,Redirect,useHistory} from 'react-router-dom'
import {Search} from "./pages/Search/Search";
import {useSelector,useDispatch} from 'react-redux'
import {useEffect} from 'react'
import {getBuycar} from "./redux/BuyCar/slice";
import {RootState} from "./redux/store/store";
import PagePayment from "./pages/PagePayment/PagePayment";
import './App.css';
import PageBuycar from "./pages/PageBuyCar/PageBuyCar";
interface propsType{
    component:any,
    isAuthenticated:boolean,
    path:string
}
const PrivateRoute:React.FC<propsType>=({component,isAuthenticated,path})=>{
    const routeComponent=(props:any)=>{
        return isAuthenticated ? (
            React.createElement(component,props)
        ) : (<Redirect to={{pathname:'/login'}}/>)
    }
    return (<Route render={routeComponent} path={path}/>)
}

function App() {
    const isAuthenticated=useSelector((state:RootState)=>state.userlogin.token)!==null
    const token=useSelector((state:RootState)=>state.userlogin.token)
    const dispatch=useDispatch()
    useEffect(()=>{
        if(token){
            dispatch(getBuycar(token))
        }
    },[])
      return (
          <div className="App">
              <BrowserRouter>
                  <Switch>
                  <Route path="/home" component={Home}></Route>
                  <Route path="/detail/:touristid" component={Detail}></Route>
                  <Route path="/login" component={Login}></Route>
                  <Route path="/register" component={Register}></Route>
                  <Route path="/search/:keyword" component={Search}></Route>
                  <Route path="/search" component={Search}></Route>
                  <Route path="/pagepayment" component={PagePayment}></Route>
                  <PrivateRoute isAuthenticated={isAuthenticated} component={PageBuycar} path='/buycar'></PrivateRoute>
                  <Redirect to="/home"/>
                  </Switch>
              </BrowserRouter>
          </div>
      );
}

export default App;
